#include "SeqList.h"

void SLinit(SL* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->size = 0;
}

void Printf(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
		printf("%d ", ps->arr[i]);
	printf("\n");
}
void SpaceCheck(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int Newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLdatatype* tmp = (SLdatatype*)realloc(ps->arr, Newcapacity * sizeof(SLdatatype));
		if (tmp == NULL)
		{
			perror("Realloc faild !");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = Newcapacity;
	}
}
void PushBackData(SL* ps, SLdatatype x)
{
	assert(ps);
	SpaceCheck(ps);
	ps->arr[ps->size] = x;
	ps->size++;
}

void PushBackPopData(SL* ps)
{
	assert(ps);
	ps->size--;
}

void PushFrontData(SL* ps, SLdatatype x)
{
	assert(ps);
	SpaceCheck(ps);
	for (int i = ps->size; i >= 1; i--)
		ps->arr[i] = ps->arr[i - 1];
	ps->arr[0] = x;
	ps->size++;
}

void PopFrontData(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size - 1; i++)
		ps->arr[i] = ps->arr[i + 1];
	ps->size--;
}

void SLInsert(SL* ps, int pos, SLdatatype x)
{
	assert(ps&&0<=pos&&pos<ps->size);
	SpaceCheck(ps);
	for (int i = ps->size; i >= pos+1; i--)
		ps->arr[i] = ps->arr[i - 1];
	ps->arr[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps && 0 <= pos && pos < ps->size);
	for (int i = pos; i < ps->size - 1; i++)
		ps->arr[i] = ps->arr[i + 1];
	ps->size--;
}

int SLFind(SL* ps, SLdatatype x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
		if (ps->arr[i] == x)
			return  i;

	return;
}

void SLDestroy(SL* ps)
{
	assert(ps);
	free(ps->arr);
	ps->arr = NULL;
	ps->capacity = ps->size = 0;
}

